package com.cn.wanxi.servlet;

import com.cn.wanxi.dto.NewsModelDto;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.impl.NewsServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/frontNews")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//         1.拿到页面的值,首先判断前台拿过来的值是否有效
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
//         2.将页面的值封装到model对象
        PageModel pageModel = new PageModel();
        int num = 0;
        num = pageNum == null || "".equals(pageNum) ? 0 : Integer.parseInt(pageNum);
        pageModel.setPageNum(num < 2 ? 1 : num);
        pageModel.setPageSize(pageSize == null || "".equals(pageSize) ? 8 : Integer.parseInt(pageSize));
//         3.调用service层
        INewsService newsService = new NewsServiceImpl();
        NewsModelDto newsModel = newsService.getNewsModel(pageModel);
//         4.返回页面（返回数据）

        JSONArray jsonArray = JSONArray.fromObject(newsModel);
        System.out.println(jsonArray.toString());
        resp.getWriter().println(jsonArray);
    }
}
